package com.gvsoft.communication.client.status;

import com.gvsoft.communication.client.Client;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgClient
 * Author: zhaoqiubo
 * Date: 15/8/8
 * Time: 下午5:59
 * Desc: 断线重连线程：一种是正常断线，服务端会给出事件；另一种异常断线，需要维持链路线程给出标记；
 */
public class ReconnectThread extends Thread {

    private final static Logger logger = LogManager.getLogger("client");
    private Client client;
    public boolean isInterrupt = false;

    public ReconnectThread(Client client, String name) {
        this.client = client;
        this.setName(name);
    }

    public void setInterrupt() {
        this.isInterrupt = true;
        super.interrupt();
    }

    public void run() {
        while (!isInterrupt) {

            if (client.getnSocket().isReconnect()) {
                client.releaseAll();
                ThreadGroup tg = Thread.currentThread().getThreadGroup();
                logger.info(client.getUserId() + "正在重新连接服务器…………当前服务器状态【" + client.getClientStatus() + "】,当前活跃线程数量：【" + tg.activeCount() + "】");
                client.startDispacher(client.getUserId());
            }
            try {
                Thread.sleep(client.getCfg().getReconnectCycle() * 1000);
            } catch (InterruptedException e) {
                logger.error("ReconnectThread is interrupted:" + e.getMessage());
            }
        }
    }
}
